import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserProFileApi, login } from '@/api/user'

const state = () => ({
  token: getToken(),
  userInfo: {}
})

// 同步修改
const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户资料
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 移除用户资料
  removeUserInfo() {
    state.userInfo = {}
  }
}
// 异步修改
const actions = {
  // 登录的操作
  async loginAction(context, payload) {
    // 1.发起网络请求，得到token
    const res = await login(payload)
    console.log(res)
    // 2.将token 这是给state中
    context.commit('setToken', res)
  },
  async getUserProFileAction(context) {
    const res = await getUserProFileApi()
    context.commit('setUserInfo', res)
  },
  // 退出的action操作
  logout({ commit }) {
    // 清楚用户资料  token
    commit('removeToken')
    commit('removeUserInfo')
  }
}

// 暴露
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
